﻿using System;
using System.Collections;
using System.IO;
using System.Xml.Serialization;

public class SearchTags
{
    [XmlArray("SearchTags")]
    [XmlArrayItem("Tag", typeof(SearchTag))]
    public ArrayList List;

    public SearchTags()
    {
        List = new ArrayList();
    }

    public SearchTags(string xmlFile)
    {
        using (var fileStream = new FileStream(xmlFile, FileMode.OpenOrCreate, FileAccess.Read))
        {
            List = new ArrayList();
            var s = new XmlSerializer(typeof(SearchTags));
            List = ((SearchTags)s.Deserialize(fileStream)).List;
            RemoveExpired(7);
            List.Sort(new FeaturedLinksComparer());
        }
    }

    public void Add(SearchTag tag)
    {
        List.Add(tag);
        List.Sort(new FeaturedLinksComparer());
    }

    public void Remove(SearchTag tag)
    {
        List.Remove(tag);
        List.Sort(new FeaturedLinksComparer());
    }

    public void Remove(int tagID)
    {
        for (int i = 0; i < List.Count; i++)
        {
            if (((SearchTag)List[i]).ID == tagID)
            {
                List.Remove(List[i]);
                break;
            }
        }
    }

    public void RemoveExpired(int Days)
    {
        for (int i = 0; i < List.Count; i++)
        {
            if (((SearchTag)List[i]).LastSearchDate.AddDays(Days) < DateTime.Now)
            {
                List.Remove(List[i]);
                break;
            }
        }
    }

    public void SaveToXml(string xmlFile)
    {
        var s = new XmlSerializer(GetType());
        using (var fileStream = new FileStream(xmlFile, FileMode.Truncate, FileAccess.Write))
        {
            s.Serialize(fileStream, this);
        }
    }

    public SearchTag FindTag(string title)
    {
        foreach (SearchTag tag in List)
            if (tag.Title == title)
                return tag;
        return new SearchTag();
    }
}

public class SearchTag
{
    public int ID;
    public DateTime LastSearchDate;
    public int Occurances;
    public string Title;
    public string URL;

    public SearchTag()
    {
        ID = 0;
        Occurances = 1;
        URL = string.Empty;
        Title = string.Empty;
        LastSearchDate = DateTime.Now;
    }
}

public class FeaturedLinksComparer : IComparer
{
    #region IComparer Members

    int IComparer.Compare(object x, object y)
    {
        var o1 = (SearchTag)x;
        var o2 = (SearchTag)y;

        return o1 == null
                   ? (o2 == null ? 0 : -1)
                   : (o2 == null ? 1 : o2.LastSearchDate.CompareTo(o1.LastSearchDate));
    }

    #endregion
}